extends Node

signal  progress_changed(progress)
signal  load_done

## 加载场景路径
var _load_screen_path : String = "res://test/loadSence/loading_screen.tscn"
var _load_screen : PackedScene = load(_load_screen_path)
#加载资源
var _loaded_resource : PackedScene
var _scene_path : String
var _progress : Array = []

#true使用多线程
var use_sub_threads : bool = true

## 加载场景
func load_scene(scene_path : String) -> void:
	_scene_path = scene_path
	
	#初始化加载场景并添加到当前场景
	var new_load_screen = _load_screen.instantiate()
	
	get_tree().root.add_child(new_load_screen)
	
	#连接加载函数
	self.progress_changed.connect(new_load_screen._update_progress_bar)
	self.load_done.connect(new_load_screen._start_outro_animation)

	await Signal(new_load_screen,"loading_screen_has_full_coverage")

	start_load()
	
func  start_load() -> void:
	#加载场景
	var state = ResourceLoader.load_threaded_request(_scene_path,"",use_sub_threads)
	if  state == OK:
		set_process(true)
		
		
func _process(_delta):
	var load_status =ResourceLoader.load_threaded_get_status(_scene_path,_progress)
	match load_status:
		0,2: # 0该资源无效，或尚未使用 load_threaded_request() 加载，2加载过程中发生了错误，导致失败
			set_process(false)
			return
		1: # 加载中
			emit_signal("progress_changed",_progress[0])	
		3:  # 加载完成
			_loaded_resource = ResourceLoader.load_threaded_get(_scene_path)
			emit_signal("progress_changed",1.0)   
			emit_signal("load_done")	
			get_tree().change_scene_to_packed(_loaded_resource)
	pass		
